import React from 'react'
import {connect} from 'react-redux'
import {fetchGameAnalysisReq, fetchLineUpReq} from "../../../../../apis/nanoApi";

import {withRouter} from 'react-router-dom'
import "./lineup.css"
import qiuchang from '../../../../../res/images/web/game-room/阵容／球场平面@2x.png'
import huanren from '../../../../../res/images/web/game-room/change2@2x.png'
import wushuju from '../../../../../res/images/web/game-room/wushuju@2x.png'
import constants from "../../../../../utils/constants";
import PlayerList from "../../../../../shared-components/PlayerList/PlayerList";
import RoundPlayerIcon from "./RoundPlayerIcon/RoundPlayerIcon";
import TeamIconTitle from "../../../../../shared-components/PlayerList/TeamIconTitle/TeamIconTitle";

class Lineup extends React.Component {

    constructor(props) {
        super(props)
        this.matchId = this.props.match.params.gameId
        this.state = {
            fetchEnd: false,
            lineup: {},
            injury: {},
        }
    }

    componentDidMount() {
        // let ctn = getDom('.am-tabs-pane-wrap-active')
        //
        // const scrollCallback = _.throttle(() => {
        //     const content = this.ctnContent
        //     const contentHeight = content.scrollHeight
        //     const afterScrollHeight = document.documentElement.clientHeight - 64 - 43.5
        //     const top = ctn.scrollTop
        //     if (top > 0 && afterScrollHeight < contentHeight) {
        //         this.props.setAtTop(false)
        //     } else if (top === 0) {
        //         this.props.setAtTop(true)
        //     }
        // }, 100)
        // if (ctn) {
        //     bindEvent(ctn, 'scroll', scrollCallback)
        // }
        // this.get().then(resp => {
        //     const data = JSON.parse(resp.data.ok)
        //     this.setState({
        //         data: data,
        //     })
        // })
        Promise.all([this.get(), this.injury()]).then(values => {
            const [lineupRes, injuryRes] = values
            this.setState({
                fetchEnd: true,
                lineup: JSON.parse(lineupRes.data.ok),
                injury: JSON.parse(injuryRes.data.ok).injury,
            })
        })
            .then(() => {
                this.props.setContentCtn(this.ctnContent, this.props.bindScrollEvent)
            })
    }

    get() {
        return fetchLineUpReq(
            {
                id: this.matchId,
            }, false,
        )
    }

    injury() {
        return fetchGameAnalysisReq(
            {
                id: this.matchId,
            }, false,
        )
    }

    shortenName = (name) => {
        const isLongName = name.indexOf('·') > -1
        let lastName = name
        if (isLongName) {
            let arr = name.split('·')
            lastName = arr[arr.length - 1]
        }
        return lastName
    }

    renderPlayer = (player, alignLeft = true) => {
        if (player) {
            const {
                name,
                logo,
                position,
                shirt_number,
            } = player

            return <>
                <RoundPlayerIcon
                    imgSrc={constants.player_icon_prefix + logo}
                    width='32px'
                    style={{margin: alignLeft ? '0 8px 0 0' : '0 0 0 8px', order: alignLeft ? '' : 1,}}
                />
                <div
                    style={{
                        textAlign: alignLeft ? '' : 'right',
                        order: alignLeft ? '' : 0,
                    }}
                >
                    <p>{this.shortenName(name)}</p>
                    {shirt_number
                        ? <span className='gray-text'>{position} - {shirt_number}号</span>
                        : <span className='gray-text'>{position}</span>
                    }
                </div>

            </>
        } else {
            return null
        }
    }

    renderTeam = (players, home = true,) => {
        return players.map(p => {

            return <div key={p.name}>
                <div
                    className='game-room-lineup-player'
                    style={{
                        left: home
                            ? `${p.x}%`
                            : `${100 - p.x}%`,
                        top: home
                            ? `${p.y / 2}%`
                            : `${50 + (100 - p.y) / 2}%`,
                        transform: 'translate(-50%, -50%)',
                    }}
                >
                    {/*<img src={constants.player_icon_prefix + p.logo} alt=''/>*/}
                    <div
                        style={{
                            background: `no-repeat url("${constants.player_icon_prefix + p.logo}") 50% 50%/cover`,
                            borderRadius: '50%',
                            height: 24,
                            width: 24,
                            margin: '0 auto',
                            marginBottom: '4px',
                        }}
                    />
                    <p>{p.shirt_number}-{this.shortenName(p.name)}</p>
                </div>
            </div>
        })
    }

    renderBench = (players,) => {
        return players.map(player => {
            return <div
                key={player.id}
                style={{
                    display: 'flex',
                    padding: '6px 8px',
                    background: 'rgba(248,248,248,0.5)',
                    marginBottom: 2,
                }}
            >
                {this.renderPlayer(player)}
            </div>

        })
    }

    render() {
        const lineup = this.state.lineup
        const injury = this.state.injury
        const game = this.props.game.currentGame

        if (Object.keys(lineup).length === 0) {

            if (this.state.fetchEnd) {
                return <div
                    style={{
                        textAlign: 'center',
                        marginTop: '40%',
                    }}
                >
                    <img src={wushuju} alt='' style={{width: 96, height: 63,}}/>
                    <p className='gray-text'>暂无数据</p>
                </div>
            }
            return null

        }

        const homeTeam = game.home_team
        const awayTeam = game.away_team
        const homeInjury = injury.home || []
        const awayInjury = injury.away || []
        const homePlayers = lineup.home
        const awayPlayers = lineup.away

        const homeStarter = homePlayers?.filter(player => player.first === 1)
        const awayStarter = awayPlayers?.filter(player => player.first === 1)
        const homeBench = homePlayers?.filter(player => player.first === 0)
        const awayBench = awayPlayers?.filter(player => player.first === 0)
        const homeRotate = homeStarter?.filter(player => player.incidents !== undefined && player.incidents.some(i => i.type === 9)) || []
        const awayRotate = awayStarter?.filter(player => player.incidents !== undefined && player.incidents.some(i => i.type === 9)) || []

        const rotateTableHeader = [
            '球员',
            <img src={huanren} alt='' style={{width: 14, height: 13,}}/>,
            '替补球员'
        ]
        const injuryTableHeader = [
            '球员',
            '',
            '原因'
        ]

        const rotateTableBodyRender = (list) => {
            let listTemplate
            if (list && list.length === 0) {
                listTemplate = <div style={{textAlign: 'center', padding: 4,}}><p>暂无数据</p></div>
            } else {
                listTemplate = list?.map(player => {
                    const rotate = player.incidents.filter(i => i.type === 9)[0]
                    const {
                        id,
                    } = player

                    if (!rotate) return null

                    const {
                        minute,
                        in_player,
                    } = rotate
                    const inPlayerDate = [...homeBench, ...awayBench,].find(p => p.id === in_player.id)

                    return <div
                        key={id}
                        className='flex-space-between-align-center player-list-table-row'
                    >
                        <div className='flex-align-center' style={{width: '50%',}}>
                            {this.renderPlayer(player)}
                        </div>
                        <div>
                            <span>{minute}'</span>
                        </div>
                        <div className='flex-align-center' style={{width: '50%', justifyContent: 'flex-end'}}>
                            {this.renderPlayer(inPlayerDate, false)}
                        </div>
                    </div>

                })
            }
            return <>
                {listTemplate}
            </>
        }

        const injuryTableBodyRender = (list) => {
            let listTemplate
            if (list && list.length === 0) {
                listTemplate = <div
                    style={{textAlign: 'center', padding: 4,}}
                >
                    <p>暂无数据</p>
                </div>
            } else {
                listTemplate = list?.map(player => {
                    const {
                        id,
                        reason
                    } = player

                    return <div
                        key={id}
                        className='flex-space-between-align-center player-list-table-row'
                    >
                        <div
                            className='flex-align-center'
                            style={{width: '50%',}}
                        >
                            {this.renderPlayer(player)}
                        </div>
                        <div />
                        <div
                            className='flex-align-center'
                            style={{width: '50%', display: 'flex', justifyContent: 'flex-end',}}
                        >
                            {reason}
                        </div>
                    </div>

                })
            }
            return listTemplate
        }



        return <div className='game-room-lineup-ctn' ref={el => this.ctnContent = el}>
            <div className='game-room-lineup-ground-ctn'>
                <img src={qiuchang} alt='' className='game-room-lineup-ground'/>
                {homeStarter && this.renderTeam(homeStarter)}
                {awayStarter && this.renderTeam(awayStarter, false)}
            </div>

            {
                homeRotate.length > 0 || awayRotate.length > 0
                    ? <div className='game-room-lineup-sub-title'>
                        <p>本场换人</p>
                    </div>
                    : null
            }
            {
                homeRotate.length > 0
                && <PlayerList
                    team={homeTeam}
                    list={homeRotate}
                    tableHeadData={rotateTableHeader}
                    tableBodyRender={list => rotateTableBodyRender(list)}
                />
            }
            {
                awayRotate.length > 0
                && <PlayerList
                    team={awayTeam}
                    list={awayRotate}
                    tableHeadData={rotateTableHeader}
                    tableBodyRender={list => rotateTableBodyRender(list)}
                />
            }

            <div className='game-room-lineup-sub-title'>
                <p>本场替补</p>
            </div>
            <div
                style={{
                    background: '#fff',
                    display: 'flex',
                    padding: '12px 8px',
                }}
            >
                <div style={{width: '50%', marginRight: '5px',}}>
                    <TeamIconTitle
                        team={homeTeam}
                        style={{
                            justifyContent: 'flex-start',
                            marginBottom: '8px',
                        }}
                    />
                    <div>
                        {homeBench && this.renderBench(homeBench,)}
                    </div>

                </div>
                <div style={{width: '50%',}}>
                    <TeamIconTitle
                        team={awayTeam}
                        style={{
                            justifyContent: 'flex-start',
                            marginBottom: '8px',
                        }}
                    />
                    <div>
                        {awayBench && this.renderBench(awayBench,)}
                    </div>
                </div>
            </div>
            {homeInjury.length > 0 || awayInjury.length > 0
                ? (<div className='game-room-lineup-sub-title'>
                    <p>伤停情况</p>
                </div>)
                : null
            }
            {homeInjury.length > 0
                ? (
                    <PlayerList
                        team={homeTeam}
                        list={homeInjury}
                        tableHeadData={injuryTableHeader}
                        tableBodyRender={list => injuryTableBodyRender(list)}
                    />
                )
                : null
            }
            {awayInjury.length > 0
                ? (
                    <PlayerList
                        team={awayTeam}
                        list={awayInjury}
                        tableHeadData={injuryTableHeader}
                        tableBodyRender={list => injuryTableBodyRender(list)}
                    />
                )
                : null
            }


        </div>
    }

}

const mapState = state => ({
    game: state.game,
})

export default connect(mapState)(withRouter(Lineup))
